package com.emm.yixun.jobs;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.common.model.ActOaLog;
import com.emm.yixun.common.model.dto.ActOaLogDto;
import com.emm.yixun.common.model.enums.OperationStatusEnum;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.jobs.common.HttpUtil;
import com.emm.yixun.jobs.config.PmoConfig;
import com.emm.yixun.system.service.ActOaLogServiceFacade;
@Component
public class ActTackSendToOAJob {
	 private static Logger   logger  = LoggerFactory.getLogger(ActTackSendToOAJob.class);

	 @Autowired
	 private ActOaLogServiceFacade actOaLogServiceFacade;
	 @Autowired
	 private PmoConfig pmoConfig;
	 @Scheduled(cron="${quartz.cron.actTaskSendToOa}")
	 public void actTackSendToOA(){
    	 logger.info("act task send to oa job start..........");
    	 //生成时间段内需推送的任务集合
    	 actOaLogServiceFacade.buildSendTask(null,null);
    	 //推送任务至OA
    	 sendMsgToOa();
    	 //推送根据返回值,更新被推送数据成功状态
    	 logger.info("act task send to oa job end..........");
	 }
	 
	 /**
	  * 将待推送的已完成的流程任务推送至OA
	  * 1、推送前一天流程中完成的任务
	  * 2、推送历史失败任务
	  */
	 public void sendMsgToOa(){
		 String url = pmoConfig.getActTaskOaUrl();
		 ResponseList<ActOaLog> aolListRes  =  actOaLogServiceFacade.findSendtoOaListByDto();
		 if(aolListRes.isSuccess()){
    		 List<ActOaLog> aolList = aolListRes.getEntity();
    		 if(null != aolList && aolList.size() > 0){
    			 for(ActOaLog aol: aolList){
    		    	 String operationStatus = OperationStatusEnum.FAILURE.getNo();
    		    	 String result = "send to oa exception: ";
    		    	 try{
    		    		 result = HttpUtil.doPost(url, aol.getReceiveSendMsg(),"UTF-8");
        		    	 if(StringUtils.isNotEmpty(result)){
        		    		 JSONObject object = JSONObject.parseObject(result);
        		    		 String code = object.getString("code");
        		    		 if("200".equals(code)){
        		    			 operationStatus = OperationStatusEnum.SUCCESS.getNo();
        		    		 }
        		    	 }
    		    	 }catch(Exception ex){
    		    		 ex.printStackTrace();
    		    		 result = "send to oa exception: " + ex.getMessage();
    		    		 logger.error("推送任务至OA异常: ", ex);
    		    	 }
    		    	 ActOaLogDto aolDto = new ActOaLogDto();
    		    	 aolDto.setId(aol.getId());
    		    	 aolDto.setOperationStatus(operationStatus);
    		    	 aolDto.setReturnMsg(result);
    		    	 actOaLogServiceFacade.updateByPrimaryKey(aolDto, true);
        		 }
    		 }
    	 }
	 }

}
